package main

import (
	"fmt"
	"sync"

	"example.com/testmutex/testmutex"
)

func main() {
	fmt.Println("Demo with sync.Mutex:")
	runDemo(&testmutex.MutexCounter{})

	fmt.Println("\nDemo with sync.RWMutex:")
	runDemo(&testmutex.RWMutexCounter{})
}

// runDemo 模拟多个读协程与少量写协程并发访问共享计数器
func runDemo(counter testmutex.Counter) {
	const (
		readers         = 8
		writers         = 2
		readIterations  = 1000
		writeIterations = 200
	)

	var wg sync.WaitGroup

	// 启动读协程
	for i := 0; i < readers; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			for j := 0; j < readIterations; j++ {
				_ = counter.Read()
			}
		}(i)
	}

	// 启动写协程
	for i := 0; i < writers; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			for j := 0; j < writeIterations; j++ {
				counter.Increment()
			}
		}(i)
	}

	wg.Wait()
	fmt.Printf("Final counter value: %d\n", counter.Read())
}
